#!/bin/sh
# parameter 1: tidb port
# parameter 2: tidb password
# parameter 3: optional, tidb config file

set -eu

tmp_config="/tmp/dm_test/tidb.toml"

PORT=$1
PASSWORD=$2
CONFIG=""

if [ "$#" -ge 3 ]; then
	cat $3 >$tmp_config
else
	# turn on collation framework https://docs.pingcap.com/tidb/stable/character-set-and-collation#new-framework-for-collations
	rm $tmp_config || true
	cat >$tmp_config <<EOF
new_collations_enabled_on_first_bootstrap = true

[experimental]
enable-new-charset = true

EOF
fi

TEST_DIR=/tmp/dm_test

echo "Starting TiDB on port ${PORT}"
bin/tidb-server \
	-P ${PORT} \
	--config "$tmp_config" \
	--log-file "$TEST_DIR/downstream/tidb/log/tidb.log" &

echo "Verifying TiDB is started..."
i=0
while ! mysql -uroot -h127.0.0.1 -P${PORT} --default-character-set utf8 -e 'select * from mysql.tidb;'; do
	i=$((i + 1))
	if [ "$i" -gt 10 ]; then
		echo 'Failed to start TiDB'
		exit 1
	fi
	sleep 2
done

# if user test is already exist, add || true to avoid exit with 2
mysql -uroot -h127.0.0.1 -P${PORT} --default-character-set utf8 -e "CREATE USER 'test'@'%' IDENTIFIED BY '$PASSWORD';" || true
mysql -uroot -h127.0.0.1 -P${PORT} --default-character-set utf8 -e "GRANT ALL PRIVILEGES ON *.* TO 'test'@'%' WITH GRANT OPTION;" || true
mysql -uroot -h127.0.0.1 -P${PORT} --default-character-set utf8 -e "SET @@global.tidb_enable_clustered_index = 'INT_ONLY'"
mysql -uroot -h127.0.0.1 -P${PORT} --default-character-set utf8 -e "SET @@global.tidb_ddl_enable_fast_reorg = 0" || true
